﻿/***************************  Ccay IGrid colSort  ***********************************/
(function(IGrid){
	/** 过滤比较符号表
	 */
	var OPTypes =["equals", "unEqual", "greatThan" , "lessThan", "equalsGreatThan", "equalsLessThan",
		"includes", "exclude", "prefix", "suffix", "empty", "unEmpty" ];
	var RelationText = Ccay.Local.getCurrLanguage() == "zh_CN" ? ["并","或"] : ["AND","OR"];
	var RelationTextAnd = RelationText[0],RelationTextOr =RelationText[1]
	var CustomTypeEnum=[
		{value : "equals", text :$i18n("ccay.common.filtercustom.equals")},
		{value : "unEqual",  text :$i18n("ccay.common.filtercustom.unEqual")},
		{value : "greatThan",  text :$i18n("ccay.common.filtercustom.greatThan")},
		{value : "equalsGreatThan",  text :$i18n("ccay.common.filtercustom.equalsGreatThan")},
		{value : "lessThan",  text :$i18n("ccay.common.filtercustom.lessThan")},
		{value : "equalsLessThan",  text :$i18n("ccay.common.filtercustom.equalsLessThan")},
		{value : "includes", text :$i18n("ccay.common.filtercustom.includes")},
		{value : "exclude",  text :$i18n("ccay.common.filtercustom.exclude")},
		{value : "prefix",  text :$i18n("ccay.common.filtercustom.prefix")},
		{value : "suffix",  text :$i18n("ccay.common.filtercustom.suffix")}
	];
		
	var OPEnum ={
		equals : 0, unEqual : 1, greatThan : 2, lessThan: 3, equalsGreatThan : 4, equalsLessThan : 5,
		includes : 6, exclude:7 , prefix :8, suffix: 9, empty: 10,  unEmpty : 11
	}
	
	var OperationFactory = $.IFactory();
	
	OperationFactory.add("def,equals",{
		compare : function(value, compareValue){
			return value == compareValue ? true : false;
		}
	});
	
	OperationFactory.add("unEqual",{
		compare : function(value, compareValue){
			return value != compareValue ? true : false;
		}
	});
	
	OperationFactory.add("greatThan",{
		compare : function(value, compareValue){
			return  value > compareValue;
		}
	});
	
	OperationFactory.add("lessThan",{
		compare : function(value, compareValue){
			return  Ccay.DataHelper.hasValue(value) &&  value < compareValue;
		}
	});
	
	OperationFactory.add("equalsGreatThan",{
		compare : function(value, compareValue){
			return  value >= compareValue;
		}
	});
	
	OperationFactory.add("equalsLessThan",{
		compare : function(value, compareValue){
			return Ccay.DataHelper.hasValue(value) &&  value <= compareValue;
		}
	});
	
	OperationFactory.add("includes",{
		compare : function(value, compareValue){
			return value && value.indexOf(compareValue) > -1 ? true : false;
		}
	});
	
	OperationFactory.add("exclude",{
		compare : function(value, compareValue){
				return value && value.indexOf(compareValue) == -1 ? true : false;
		}
	});
	
	OperationFactory.add("prefix",{
		compare : function(value, compareValue){
			return value && value.indexOf(compareValue) == 0 ? true : false;
		}
	});
	
	OperationFactory.add("suffix",{
		compare : function(value, compareValue){
			if(value){
				var lastIndex = value.lastIndexOf(compareValue);
				return lastIndex >= 0 && lastIndex == value.length - compareValue.length ? true : false;
			}
			return false;
		}
	});
	
	OperationFactory.add("empty",{
		compare : function(value, compareValue){
			return !Ccay.DataHelper.hasValue(value);
		}
	});
	
	OperationFactory.add("unEmpty",{
		compare : function(value, compareValue){
			return Ccay.DataHelper.hasValue(value);
		}
	});
	
	OperationFactory.add("today",{
		compare : function(value){
			return dataFilter.filterItems(this.getFilter(),value,"date");
		},
		
		getFilter : function(){
			var date = new Date(), today = new Date( date.getFullYear(), date.getMonth(), date.getDate()),
			tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
			return [{operation : "equalsGreatThan", value : today }, {operation : "lessThan", value : tomorrow }]
		}
	});
	
	OperationFactory.add("week",{
		compare : function(value){
			return dataFilter.filterItems(this.getFilter(),value,"date");
		},
		
		getFilter : function(){
			var monday, date = new Date(), today = new Date( date.getFullYear(), date.getMonth(), date.getDate()), day = today.getDay();
			if(day == 0){
				monday = new Date( date.getFullYear(), date.getMonth(), date.getDate() - 6 )
			}else{
				monday = new Date( date.getFullYear(), date.getMonth(), date.getDate() - day + 1 )
			}
			var nextMondy = new Date( monday.getTime() + 7 * 24 * 60 * 60 * 1000);
			return [{operation : "equalsGreatThan", value : monday }, {operation : "lessThan", value : nextMondy }]
		}
	});
	
	OperationFactory.add("month",{
		compare : function(value){
			return dataFilter.filterItems(this.getFilter(),value,"date");
		},
		
		getFilter : function(){
			var date = new Date(), minDate = new Date(date.getFullYear(), date.getMonth(), 1), maxDate = minDate.addMonth(1);
			return [{operation : "equalsGreatThan", value : minDate }, {operation : "lessThan", value : maxDate }]
		}
	});
	
	OperationFactory.add("threeMonth",{
		compare : function(value){
			return dataFilter.filterItems(this.getFilter(),value,"date");
		},
		
		getFilter : function(){
			var date = new Date(), maxDate = new Date(date.getFullYear(), date.getMonth() + 1, 1), 
			minDate =new Date(date.getFullYear(), date.getMonth()-2, 1);
			return [{operation : "equalsGreatThan", value : minDate }, {operation : "lessThan", value : maxDate }]
		}
	});
	
	OperationFactory.add("year",{
		compare : function(value){
			return dataFilter.filterItems(this.getFilter(),value,"date");
		},
		
		getFilter : function(){
			var date = new Date(), maxDate = new Date(date.getFullYear() + 1,0, 1), minDate =new Date(date.getFullYear(),0, 1);
			return [{operation : "equalsGreatThan", value : minDate }, {operation : "lessThan", value : maxDate }]
		}
	});
	
	var FilterTools =$.IFactory({
			parseValue : function(value){
				return value;
			},
			getDefaultFilterItems : function(){
				return null;
			}
		}
	);
	
	FilterTools.add("number,integer,currency,floatRequ",{
		equals : function(value, compareValue){
			return value === compareValue * 1 ? true : false;
		},
		unEqual : function(value, compareValue){
			return  value === compareValue * 1 ? false : true;
		},
		
		greatThan : true,
		lessThan : true,
		equalsGreatThan : true,
		equalsLessThan : true,
		empty : true,
		unEmpty : true

	});
	
	FilterTools.add("def,string",{
		equals : true,
		unEqual : true,
		includes : true,
		exclude : true,
		prefix : true,
		suffix :true,
		empty : true,
		unEmpty : true
	}); 

	FilterTools.add("boolean,bool",{
		equals : true,
		unEqual : true,
		empty : true,
		unEmpty : true
	});

	FilterTools.add("date,datetime",{
		equals : function(val1, val2){
			var type = typeof val1
			if(type == "string"){
				return val1 == val2 ? true : false;
			}else{
				return val1 * 1 == val2 * 1 ? true : false;
			}
		},
		unEqual : function(value, compareValue){
			return !FilterTools.get("date").equals(value, compareValue)
		},
		
		greatThan : true,
		lessThan : true,
		equalsGreatThan : true,
		equalsLessThan : true,
		empty : true,
		unEmpty : true,
		today :true,
		week :true,
		month : true,
		threeMonth :true,
		year :true,
		getDefaultFilterItems : function(){
			return [
				{operation : "today", unique : true},
				{operation : "week", unique : true},
				{operation : "month", unique : true},
				{operation : "threeMonth", unique : true},
				{operation : "year", unique : true}
			];
		}
	});
	
	FilterTools.add("enum,lookup,ldap,country,country,area,iCurrency,pbi",{
		equals : true,
		unEqual : true,
		empty : true,
		unEmpty : true
	});
	
	var dataFilter = IGrid.Filter = {
		
		init : function( grid, op ){
			op.contextMenu=true;
			op.headMenuOp = {
				panelBegin : "<ul class='ccay-igrid-filter'>",
				item : "<li class='ccay-contextmen-item ${css} ${parent}' ${click} op='${op}' val='${value}' >${#icon}${#text}${#children}</li>",
				mode : "click",
				fixPanel : ".ccay-igrid-content",
				target : "td[field].sort,li[field].sort",
				fnDynamicMenu:function(target,op,data){
					menus = dataFilter.buildMenus(grid, target.attr("field"),target);
					if(menus.length == 0){
						return null;
					}
					var field = target.attr("field"),
						exists = grid.op._filters ? grid.op._filters[field] : null,
						// 该列的设置
						fieldOp = grid.op._columnMap[field];
					
					//if(exists/*  && (!grid.op._cusFilters ||  !grid.op._cusFilters[field])*/){
					$.nodeEach(menus,"children",function(){
						var resourceVal = this.value && this.value.valueOf(),
							menu = this, 
							op = this.op, 
							val;
						// 避免值为0时被当做空值
						(resourceVal || resourceVal == "0") ? val = resourceVal : val = "" ;
						// 升序降序选中处理
						if(menu.children && grid.op.allowSort && grid.op.sort && (grid.op.sort).indexOf(fieldOp.sortField) > -1){
							if(menu.children.length == 2){
								$.each(menu.children, function(i,value){
									// 升序选中
									if(value.css == "asc" && (grid.op.sort).indexOf("asc") > -1){
										value.icon += " active-bg";
									// 否则降序选中
									}else if(value.css == "desc" && (grid.op.sort).indexOf("desc") > -1){
										value.icon += " active-bg";
									}
								})
							}
						};
						
						var hasCusFilter = grid.op._cusFilters && grid.op._cusFilters[field],
							hasInputFilter = grid.op._inputFilters && grid.op._inputFilters[field];
						// 筛选模式的图标选中处理
						// 非输入非自定义筛选；menu.icon = "yes active-bg" 打钩的图标
						!hasCusFilter && !hasInputFilter && op && exists && $.each(exists,function(){
							var val2 =  this.value && this.value.valueOf();
							// op == "dayFilter" 日期型的枚举
							if((this.operation == op || (op == "dayFilter" && this.operation == "equalsGreatThan")) && val2 == val){
								menu.css ? (menu.css += " selected") : (menu.css = "selected") ;
								menu.icon = "yes active-bg";
							};
						});
						// 输入筛选 
						if(hasInputFilter && menu.css == "igrid-input-filter"){
							menu.icon =　"yes active-bg";
						}
						// 自定义筛选
						if(hasCusFilter && menu.css == "filter-custom selected"){
							menu.icon += 　" active-bg";
						}
					});
					//}
					target.data("menus", menus);
					return menus;
				},
				callback:function(target,selector,op){
					dataFilter.popMenuCallback(grid,target,selector,op);
				}
			};
		},
		
		//上下文菜单的回调
		popMenuCallback : function(grid,target,selector,op){
			// 初始化区域
			Ccay.UI.init(selector);
			// 存在输入筛选时绑定事件
			var inputFilter = selector.find(".igrid-input-filter");
			if(inputFilter.length > 0){
				// 按钮事件绑定
				inputFilter.find(".filter-confirm-btn").click(function(){
					dataFilter.filterAreaConfirm(target,selector);
				});
				inputFilter.find(".filter-cancel-btn").click(function(){
					selector.hide();
				});
				inputFilter.find(".filter-reset-btn").click(function(){
					var input,
					inputContainer = selector.find(".filter-input"),
					isEquals = $(".filter-operation > :checked").val() == "equals";
					// 日期为等于时
					if(isEquals){
						inputContainer.find(".equals").show();
						inputContainer.find(".range").hide();
					// 日期为区间时
					}else{
						inputContainer.find(".range").show();
						inputContainer.find(".equals").hide();
					} 
				});
				// 获得输入框
				var inputArea = inputFilter.find(".filter-input > :input:visible");
				
				// 日期处理 ; radio点击事件
				if(inputArea.hasClass('ccay-calendar')){
					inputFilter.addClass("date-filter");
					dataFilter.dateRadioClick(grid,target,inputFilter,selector);
					// 值改变后的焦点处理
					inputFilter.find(".filter-input > :input").bind("change",function(){
						Ccay.UI.setInputFocus($(this), null, false);
					})
				}
				// 回写值
				dataFilter.reSetInputValue(grid, target, inputArea, selector);
				
				// input焦点
				Ccay.UI.setInputFocus(inputArea.first(), null, false);
				// 回车事件
				inputFilter.delegate(":input","keydown",function(e){
					if(e.keyCode == 13 && !$(this).hasClass("ccay-user")){
						dataFilter.filterAreaConfirm(target,selector);
					}
				})
			};
			// 多选枚举的按钮绑定事件
			var enumFilterBtn = selector.find(".filter-enumable-btn");
			if(enumFilterBtn.length > 0){
				//确认筛选 按钮
				enumFilterBtn.find(".applyfilter").click(
					function(){
						dataFilter.applyMultiFilter($(this),grid);
						selector.hide()
					});
				// 取消 按钮
				enumFilterBtn.find(".cancelfilter").click(
					function(){
						selector.hide()
					});
			}
		},
		// 根据列的数据类型初始化过滤区
		buildFilterArea:function(col,grid){
			// 排除布尔和枚举类型
			if(col.filter.input == false || $.inArray(col.type,["bool","boolean","enum"]) > -1){
				return "";
			}
			var items = [], 
				i18nKey = "ccay.common.filtercustom.",
				operationArea = "",
				operationArray = [];
				inputArea = "<input type='text' class='filter-input-area' name='_filterInput' autocomplete='off' maxlength='100' />";
			// string类型定义过滤类型，默认equats，prefix，includes三种
			if(col.filter !== false){
				operationArray = [{operation:"equals"},{operation:"prefix"},{operation:"includes",checked:true}];
			}
			// 自定义
			if($.isArray(col.filter.input)){
				operationArray = col.filter.input;
			}
			// 最多3项
			for(var i = 0,ele; ele = operationArray[i]; i++){
				if(i > 2){
					break;
				}
				operationArea += "<input type='radio' name='_filterOperation' id='{3}' value='{0}' {1}/><label for='{3}'>{2}</label>".formatValue(ele.operation,ele.checked ? "checked" : "",$i18n(i18nKey + ele.operation),"_filter_"+ele.operation);
			};
			// 整型
			if(col.type == "integer" || col.type == "int"|| col.type == "floatRequ"){
				operationArea = "<input type='radio' name='_filterOperation' value='greatThan' id='_filter_greatThan'/><label for='_filter_greatThan'>{0}</label><input type='radio' name='_filterOperation' value='equals' id='_filter_equals' checked /><label for='_filter_equals'>{1}</label><input type='radio' name='_filterOperation' value='lessThan' id='_filter_lessThan'/><label for='_filter_lessThan'>{2}</label>".formatValue($i18n(i18nKey+'greatThan'),$i18n(i18nKey+'equals'),$i18n(i18nKey+'lessThan'));
				inputArea = "<input type='text' class='filter-input-area number' name='_filterInput' autocomplete='off' maxlength='100' />";
			// 日期型
			}else if(col.type == "date" || col.type == "datetime"){
				var isEqualsFilter = true;
				if(grid.op._inputFilters[col.field] && grid.op._inputFilters[col.field].length > 0 && grid.op._inputFilters[col.field][0].operation != "equals"){
					isEqualsFilter = false;
				}
				operationArea = "<input type='radio' name='_filterOperation' value='equals' id='_filter_equals' {0} /><label for='_filter_equals'>{1}</label><input type='radio' name='_filterOperation' value='range' id='_filter_range' {2}/><label for='_filter_range'>{3}</label>".formatValue(isEqualsFilter?"checked":"",$i18n(i18nKey+'equals'),isEqualsFilter?"":"checked",$i18n(i18nKey+'range'));
				if(grid.op._inputFilters[col.field] && grid.op._inputFilters[col.field].length > 0 && grid.op._inputFilters[col.field][0].operation != "equals"){
					inputArea = "<input type='text' name='_filterEqualsDate' class='equals init ccay-calendar date' autocomplete='off' maxlength='50' style='display:none' /><input type='text' name='_filterStartDate' id='_filterStartDate' class='range init ccay-calendar date dateCompareB' compareto='#_filterEndDate' autocomplete='off' maxlength='50'/><span class='range range-flag'></span><input type='text' name='_filterEndDate' id='_filterEndDate' compareTo='#_filterStartDate' class='range init ccay-calendar date dateCompare' autocomplete='off' maxlength='50'/>";
				}else{
					inputArea = "<input type='text' name='_filterEqualsDate' class='equals init ccay-calendar date' autocomplete='off' maxlength='50' /><input type='text' name='_filterStartDate' id='_filterStartDate' class='range init ccay-calendar date dateCompareB' compareto='#_filterEndDate' autocomplete='off' maxlength='50' style='display:none'/><span class='range range-flag' style='display:none'></span><input type='text' name='_filterEndDate' id='_filterEndDate' compareTo='#_filterStartDate' class='range init ccay-calendar date dateCompare' autocomplete='off' maxlength='50' style='display:none'/>";
				}
			// 人员
			}else if(col.type == "user" || col.type == "ldap"){
				// 只有等于,隐藏
				operationArea = "<input type='radio' name='_filterOperation' value='equals' id='_filter_equals' checked style='display: none;' />";
				// filter:{input:{valueField:""}}可指定userId或者userAccount，不指定则默认userId
				inputArea = "<input type='text' class='init ccay-user filter-input-area' name='_filterInput' autocomplete='off' maxlength='100' valueField='{0}' />".formatValue(col.filter && col.filter.input && col.filter.input.valueField || "userId");;
			}
			// dom
			items.push("<form class='init ccay-form'>");
			items.push("<ul class='input-filter-div' tabIndex='1'><li class='filter-operation'>");
			items.push(operationArea);
			items.push("</li><li class='filter-input'>");
			items.push(inputArea);
			items.push("</li><li class='filter-btn'>");
			items.push("<input type='button' name='_filterConfirm' class='filter-confirm-btn' value='{0}' /><input type='button' name='_filterCancel' class='filter-cancel-btn' value='{1}'  /><input type='reset' name='_filterReset' class='filter-reset-btn' value='{2}' />".formatValue($i18n('ccay.common.button.ok'),$i18n('ccay.common.button.cancel'),$i18n('ccay.common.label.reset')));
			items.push("</li></ul></form>");
			
			return items.join("");
		},
		// 日期radio 事件
		dateRadioClick:function(grid,target,inputFilterArea,selector){
			inputFilterArea.find(".filter-operation > :radio").click(function(){
				var input,
					inputContainer = selector.find(".filter-input"),
					isEquals = $(this).val() == "equals";
				// 日期为等于时
				if(isEquals){
					inputContainer.find(".equals").show();
					inputContainer.find(".range").hide();
				// 日期为区间时
				}else{
					inputContainer.find(".range").show();
					inputContainer.find(".equals").hide();
				}
				// 清除值和验证错误信息
				inputContainer.find("input").ccaySetValue("").removeClass("error");
				inputContainer.find("label.error").remove();
				// 焦点
				Ccay.UI.setInputFocus(inputContainer.find("input:visible:first"), null, false);
	
				Ccay.UI.init(inputContainer);
				
				dataFilter.reSetInputValue(grid, target, inputFilterArea.find(":input:visible"),selector);
			})
		},
		// 回写填充输入值
		reSetInputValue : function(grid, target, input, selector){
			var targetValue = grid.op._inputFilters[target.attr("field")] || [],
				hasCalendar = selector.find(".ccay-calendar").length > 0,
				isStartTime,isEndTime,isEqualsTime;
			$.each(targetValue, function(i,n){
			    if(hasCalendar){
			    	isStartTime = targetValue[i].operation == "equalsGreatThan";
			    	isEndTime = targetValue[i].operation == "lessThan";
			    	isEqualsTime = targetValue[i].operation == "equals";
			    	
			    	isStartTime && selector.find("[name='_filterStartDate']").ccaySetValue(n.value);
			    	isEndTime && selector.find("[name='_filterEndDate']").ccaySetValue(n.value);
			    	isEqualsTime && selector.find("[name='_filterEqualsDate']").ccaySetValue(n.value);
			    }else{
			    	selector.find("[name='_filterInput']").ccaySetValue(n.value);
			    	selector.find(":radio[name='_filterOperation'][value='"+ n.operation +"']").attr("checked",true);
			    }
			})
		},
		// 确定按钮事件
		filterAreaConfirm:function(target, selector){
			// 验证
			if(!selector.find(".ccay-form").valid()){
				return;
			}
			var filter = [],
				inputFilter = [],
				field = target.attr("field"),
				grid = Ccay.UI.IGrid.Helper.getGrid(target).manager(),
				inputVal = selector.find(".filter-input > :input:visible").ccayGetValue() || "",
				filterval = selector.find("[name='_filterOperation']:checked").val() || "includes" ,
				isFilter = false;
			// 日期值转换处理
			if(selector.find(".ccay-calendar").length > 0){
				// 区间时
				if(selector.find("[name='_filterOperation']:checked").val() == "range"){
					var startInputvalue = selector.find("[name='_filterStartDate']").val(),
						endInputvalue = selector.find("[name='_filterEndDate']").val(),
						startTime = Ccay.Format.toDate(startInputvalue, Ccay.Config.Format.sysDate),
						endTime = Ccay.Format.toDate(endInputvalue, Ccay.Config.Format.sysDate);
					// 区间处理
					if(startTime){
						isFilter = true;
						startTime = dataFilter.dateSetting(startTime, 0);
						filter.push({operation:"equalsGreatThan",value:startTime});
						inputFilter.push({operation:"equalsGreatThan",value:startInputvalue});
					}
					if(endTime){
						isFilter = true;
						endTime = dataFilter.dateSetting(endTime, 24);
						filter.push({operation:"lessThan",value:endTime});
						inputFilter.push({operation:"lessThan",value:endInputvalue});
					}
				// 等于时 
				}else{
					if(inputVal.length > 0){
						var startTime = Ccay.Format.toDate(inputVal, Ccay.Config.Format.sysDate),
							endTime = Ccay.Format.toDate(inputVal, Ccay.Config.Format.sysDate);
					
						// 区间处理
						if(startTime && endTime){
							isFilter = true;
							startTime = dataFilter.dateSetting(startTime, 0);
							endTime = dataFilter.dateSetting(endTime, 24);
							filter.push({operation:"equalsGreatThan",value:startTime});
							filter.push({operation:"lessThan",value:endTime});
							inputFilter.push({operation:"equals",value:inputVal});
						}
					}
				}
			// 一般
			}else{
				if(inputVal){
					isFilter = true;
					filter.push({operation:filterval,value:inputVal});
					inputFilter.push({operation:filterval,value:inputVal});
				}
			};
			
			// 确认筛选
			if(isFilter){
				dataFilter.confirmFilter(grid,function(){
					grid.op._inputFilters[field] = inputFilter;
					grid.op._filters[field] = filter;
					dataFilter.addFilterStyle(target);
					// 删除自定义筛选值
					delete grid.op._cusFilters[field];
					var currentField = grid.op._columnMap[field];
					// 输入回调filter.fnInput
					if(currentField && currentField.filter && currentField.filter.fnInput){
						currentField.filter.fnInput.call(this,field,grid);
					}
				});
			}else{
				dataFilter.clearFilter(target, $(this));
			}
			// 关闭筛选下拉区
			selector.hide();
		},
		// 日期处理
		dateSetting :function(date, hours){
			date.setHours(hours);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
			// "9999-12-31" 处理，避免出现"10000-01-01"后程序报错
			if(date.getTime() >= 253402272000000){
				date.setTime(253402272000000 - 1) ;
			}
			return date;
		},
		// 菜单项点击事件
		menuClick : function(target, li){
			var field = target.attr("field"), 
				menus = target.data("menus"), 
				filter ={operation : li.attr("op") || 0, value : li.attr("val")},
				grid =  Ccay.UI.IGrid.Helper.getGrid(target).manager(),
				col = grid.op._columnMap[field],
				type = col.type || col.type || col.filter.type,
				isDayFitler = (type == "date" || type == "datetime") && li.attr("op") == "dayFilter";
			// 日期类型的枚举
			if(isDayFitler){
				var currVal = li.attr("val"),
					startTime = Ccay.Format.toDate(currVal),
					endTime = Ccay.Format.toDate(currVal);
				endTime = dataFilter.dateSetting(endTime, 24);
				var	startTimeFilter ={operation : "equalsGreatThan", value : startTime},
					endTimeFilter ={operation : "lessThan", value : endTime};
			}
			
			if(li.hasClass("filter-checkbox")){
				li.toggleClass("selected");
				target.parents(".ccay-igrid-head:first").data("contextMenuOp").selectClose = false;
				/*if(li.parent().children("li.applyfilter").length == 0){
					$.create('<li class="ccay-contextmen-item applyfilter" field={0}><a>{1}</a></li>'.formatValue(field, $i18n("ccay.common.filter.applyfilter"))).click(dataFilter.applyMultiFilter).appendTo(li.parent())
				}*/
			}else if(li.hasClass("igrid-input-filter")){
				target.parents(".ccay-igrid-head:first").data("contextMenuOp").selectClose = false;
			}else{
				dataFilter.confirmFilter(grid,function(){
					isDayFitler ? grid.op._filters[field] = [startTimeFilter,endTimeFilter] : grid.op._filters[field] = [filter];
					delete grid.op._cusFilters[field];
					delete grid.op._inputFilters[field];
					dataFilter.addFilterStyle(target);
				});
			}
		},
		
		addFilterStyle : function(target){
			if(target && !target.hasClass("filter")){
				target.addClass("filter");
			}
		},
		clearFilterStyle : function(target,all){
			target.removeClass("filter");
		},
		
		clearAllFilterStyle : function(grid){
			grid.getHeadPanel().find("td,li").removeClass("filter");
		},
		//应用多选过滤条件
		applyMultiFilter : function(btn,grid){
			var field =btn.attr("field"),
				filters =[], 
				enumValues =[],
				igridHead = btn.parents(".ccay-igrid-head:first");
			igridHead.data("contextMenuOp").selectClose  = true;
			igridHead.find("li.filter-checkbox.selected").each(function(){
				var value = $(this).attr("val");
				// 日期天数枚举的多选筛选，否则一般多选
				if($(this).attr("op") == "dayFilter"){
					var startTime = Ccay.Format.toDate(value),
						endTime = Ccay.Format.toDate(value);
					endTime = dataFilter.dateSetting(endTime, 24);
					var	startTimeFilter ={relation :1, operation : "equalsGreatThan", value : startTime},
						endTimeFilter ={relation :0, operation : "lessThan", value : endTime};
					filters.push(startTimeFilter, endTimeFilter);
				}else{
					filters.push({relation :1,operation : OPTypes[0],value :  $(this).attr("val")})
				}
			})
			
			//var grid =  Ccay.UI.IGrid.Helper.getGrid(applyBtn).manager();
			var boo = dataFilter.confirmFilter(grid,function(){
				// 删除自定义筛选和输入筛选的条件
				delete grid.op._cusFilters[field];
				delete grid.op._inputFilters[field];
				grid.op._filters[field] = filters;
				if(filters.length > 0)
					dataFilter.addFilterStyle(igridHead.find("div.ccay-contextmenu").data("target"));
				else{
					grid.getHeadPanel().find("td[field='{0}']".formatText(field)).removeClass("filter")
				}
			});

		},
		//清除当前列或所有列赏的的过滤条件
		clearFilter : function(target, li){
			var grid =  Ccay.UI.IGrid.Helper.getGrid(target).manager(),
				field = target.attr("field");
			dataFilter.confirmFilter(grid,function(){
				if(li.hasClass("filter-clearall")){
					dataFilter.clearAllFilterStyle(grid);
					grid.op._filters= {};
					grid.op._cusFilters = {};
					grid.op._inputFilters = {};
				}else{
					dataFilter.clearFilterStyle(target);
					// 清除过滤值
					delete grid.op._filters[field];
					delete grid.op._cusFilters[field];
					delete grid.op._inputFilters[field];
				}
			});
		},
		//生成列头上下文菜单项		
		buildMenus : function(grid, fieldName,target){
			//通过列名拿到列设置
			var col = grid.op._columnMap[fieldName], type = col.type || col.renderer;
			//找不到列设置，无法弹出筛选菜单
			if(!col){
				return null;
			}
			var menus = col.sortable == false ? [] : [{children : Ccay.DataHelper.copyArray(grid.op.headMenus)}];
			if(grid.op.allowFilter && col.filter && grid.op.switchMode != "search"){
				var filterItems =  this.buildFilterItemsByCol(grid, col,target),
					filterInputItem = dataFilter.buildFilterArea(col,grid);
				
				// 文本框输入过滤区
				filterInputItem.length > 0 && menus.push({
					css:"igrid-input-filter",
				    text:filterInputItem,
				    click : dataFilter.menuClick
				});
				menus = menus.concat(this.buildMenusByFilter(col, filterItems))
				// 清除当前列的过滤
				menus.push({text :"ccay.common.filter.clear",    click : this.clearFilter, css : "filter-clear", icon:"clear-filter"});
				menus.push({text :"ccay.common.filter.clearall", click : this.clearFilter, css : "filter-clearall", icon:"clear-filter"})
				if(type != "bool" && type !="boolean" && col.filter.custom !== false && col.filter.input !== false){
				    var css = grid.op._cusFilters[fieldName] ? "filter-custom selected" : "filter-custom"
					menus.push({text :"ccay.common.filter.custom",   click : this.popCusotm, css : css,icon:"customize-filter"})
				}
			}
			return menus;
		},
		//获得枚举类型
		getTypeEnum : function(col,hasEmpty){
			var opEnum =hasEmpty ? [{value :"clear",text:""}] : [], compare = FilterTools.get(col.filter.type || col.type || col.renderer)
			$.each(CustomTypeEnum,function(i, item){
				if(compare[item.value]){
					opEnum.push(item)
				}
			})
			return opEnum;
		},
		//自定义筛选弹出框
		popCusotm : function(target, li){
			var field = target.attr("field"), 
				grid = Ccay.UI.IGrid.Helper.getGrid(target).manager(),
				col = grid.op._columnMap[field], 
				type = col.type, 
				def = li.attr("op") || "equals";
			 Ccay.UI.dialog(null, "ccay.common.filter.custom", {
			 	width : 400, height :120,
			 	content : "<div></div>",
			 	imgBtn : true,
			 	okClick : function(){
			 		dataFilter.popCusotmOK(grid, this, field, target)
			 	},
			 	fnLoad : function(){
			 		var body = this.getBody().html("<div id='customfilterPanel' class='ccay-filter-custom'><ul><li  class='filter-colname'></li><li  class='filter-item'></li><li class='filter-relation clear'></li><li class='filter-item'></li><ul></div>");
			 		//初始化表单的验证
			 		var panel = this.getBody().find("#customfilterPanel").ccayValidate({
			 			errorPlacement : function(error, ctr) {
							// 设置错误标签显示的位置
							ctr.addClass('error').after(error.addClass('error').css({width :ctr.width() - 10 ,top : ctr.position().top + 20, left :  ctr.position().left}));
					}});
			 		panel.find("li.filter-colname").text(target.find("span").text());
			 		body.find("li.filter-item").each(function(i){
			 			var opDropdown = Ccay.Editor.get("enum").build($(this), {format : {data :  dataFilter.getTypeEnum(col, i==0?false:true)}});
						opDropdown.addClass("filter-operation").attr("readonly",true).attr("name","item"+i+".operation");
						i==0 && opDropdown.addClass("required");
			 		});
					var editorOp =$.extend({type : col.type, field : col.valueField || col.field, format : col.format || {} }, col.editorOp);
					panel.find("li.filter-item").append("<span class=required></span>");
					Ccay.Editor.get(col.type).build(body.find("li.filter-item"), editorOp).addClass("filter-value").addClass(type).attr("name",function(i){return "item"+i+".value"}).attr("maxLength","100").filter(":first").addClass("required");
					panel.find("li.filter-relation").append("<input type=radio name='item1.relation' checked value=0>{0}<input type=radio name='item1.relation' value=1 >{1}".formatText(RelationTextAnd,RelationTextOr)); 
					var preFilters = grid.op._cusFilters[field];
				
					// 数据填充
					if(preFilters){
						var fillData = {};
						$.each(preFilters,function(i){
							fillData["item"+i] = this;
						});
						panel.jsonData(fillData);
			 		}else{
			 			//初始化操作符
			 			body.find("li.filter-item:first ").children(":first").ccaySetValue(def);
			 		}
					panel.find("span.required:last").css("visibility","hidden");
					panel.find("input.filter-operation:last")[0].onchange = function(e){
						var val = panel.find("input.filter-operation:last").val();
						if(val == "clear" || val===""){
							panel.find("span.required:last").css("visibility","hidden");
							$("input[name='item1.value']").valid();
							
						}else{
							panel.find("span.required:last").css("visibility","visible");
						}
					}
						
			 		// 焦点和回车事件
			 		var dialog = this;
			 		setTimeout(function(){
			 			//焦点
			 			panel.find("[name='item0.value']").focus()
			 			//回车事件
				 		panel.find("[name*='item']").keydown(function(e){
				 			if(e.keyCode == 13){
				 				dataFilter.popCusotmOK(grid, dialog, field, target);
				 			}
				 		})
			 		},100);
			 	}
			 });
		},
		//自定义筛选的ok事件
		popCusotmOK :function(grid,dialog,field,target){
			var form = dialog ? dialog.getBody().find("#customfilterPanel") : this.getBody().find("#customfilterPanel"),
				input = form.find("input[name='item1.value']");
			if(form.find("input[name='item1.operation']").val()){
				input.addClass("required")
			}else{
				input.removeClass("required")
			}
			if(form.valid() === true){
				var data = form.jsonData(), filter = [];
				filter.push(data.item0);
				if(data.item1.operation){
					data.item1.relation = data.item1.relation * 1;
					filter.push(data.item1);
				}		
				dataFilter.confirmFilter(grid,function(){
					grid.op._filters[field] = filter;
					grid.op._cusFilters[field] = filter;
					delete grid.op._inputFilters[field];
					dataFilter.addFilterStyle(target);
				});
				dialog.close();
			}
	 	},
		
		buildFilterItemsByCol : function(grid, col,target){
			if(!col.filter){
				return;
			}	
			var filterItems = [],filter = col.filter, type = filter.type || col.type || col.renderer, 
			
			field = col.field, compare = FilterTools.get(type) ||  FilterTools.get("string");
			//将用户自定义的filter添加到集合中
			if(filter.defines){
				filterItems.push({children : filter.defines});
			}
			var groupMenu = {children :[]},
				existKeys =target.data("exsitKeys") || {}, 
				enumValues =target.data("filterItems") || [];
			//是否开启枚举模式开关
			if(filter.enumable){
				// ↓静态数据或服务枚举
				if(filter.values || filter.ajax || filter.lookup){
					//如果启用了远程数据源，则执行ajax查询，并解析参数
					if(filter.ajax){
						$.extend(filter.ajax,{
							async : false,
							success : function(result){
								filter.values = result.result || result || [] ;
							}
						});
						// 服务带当前已筛选条件
						var url = filter.ajax.url;
						// 如果设置有带筛选的服务时，替换处理
						if(url.indexOf("${filter}") > -1){
							url = url.formatField({filter:dataFilter.genFilterStr(grid)});
						};
						Ccay.Core.ajax($.extend(true,{}, filter.ajax, {url:url}));
					}else if(filter.lookup){//是否启用lookup数据源
						var lookupData = filter.values = [];
						if(filter.lookup === true && col.format){
							filter.lookup = col.format;
						}
						lookupData = Ccay.UI.getStaticData(filter.lookup);
						for(var i = 0, data; data = lookupData[i]; i++){
							filter.values.push({value:Ccay.DataHelper.getObj(filter.lookup.valueField || "itemCode",data),text:Ccay.DataHelper.getObj(filter.lookup.displayField || "itemName",data)});
						}
					}
					//如果设置了value值，则将values中的值转换成筛选项，添加到集合中，values可以是值数组 对象数组
					filter.values && $.each(filter.values,function(i, value){
						if(type == "date" || type == "datetime"){
							// 不需要缓存enumValues和existKeys
							dataFilter.buildDayEnumItems(filter, value, groupMenu, [], {});
						}else{
							if(typeof value == "object"){
								groupMenu.children.push({value : Ccay.DataHelper.getObj(filter.valueField || "value", value), text :  Ccay.DataHelper.getObj(filter.displayField || "text", value)})
							}else{
								groupMenu.children.push({value : value})
							}
						}
					})
				// ↓当前页数据枚举
				}else{
					// 获得storage中的数据
					var datas = (grid.op._filterStorage || grid.op.Storage).dataset;
					// 如果没有设置values，则将数据源中的列值作为筛选条件，添加到集合中
					$.each(enumValues,function(){
						groupMenu.children.push(this);
					});
					// 枚举项生成
					$.each(datas,function(i, data){
						var value = Ccay.DataHelper.getObj(field, data),text;
						if(filter.displayField){
							text = Ccay.DataHelper.getObj(filter.displayField, data)
						}
						// 时间类型处理
						if(type == "date" || type == "datetime"){
							dataFilter.buildDayEnumItems(filter, value, groupMenu, enumValues, existKeys);
						}else{
							if(Ccay.DataHelper.hasValue(value) && !existKeys[value]){
								groupMenu.children.push({value : value,text : text});
								enumValues.push({value : value,text : text});
								//将已经添加过的value，设置一个标，放在缓存中，下次不用再添加
								existKeys[value] = true;
							}
						}
					})
					// 静态数据的排序number,integer,currency升序，date datetime降序
					// 服务数据的排序由服务端控制
					if($.inArray(type, ["number","integer","currency","floatRequ"]) > -1){
						groupMenu.children.sort(function(a,b){return dataFilter.arrayCompare(b.value, a.value)});
						enumValues.sort(function(a,b){return dataFilter.arrayCompare(b.value, a.value)});
						//groupMenu.children.sort(function(a,b){return a.value > b.value});
						//enumValues.sort(function(a,b){return a.value > b.value});
					} else if($.inArray(type, ["date","datetime"]) > -1){
						groupMenu.children.sort(function(a,b){return dataFilter.arrayCompare(a.value, b.value)});
						enumValues.sort(function(a,b){return dataFilter.arrayCompare(a.value, b.value)});
						//groupMenu.children.sort(function(a,b){return b.value > a.value});
						//enumValues.sort(function(a,b){return b.value > a.value});
					};
				}
			}
			
			if(groupMenu.children.length > 0){
				if(filter.enumable && filterItems.length > 0){
					this.mergeItems(filterItems[0],groupMenu.children);
				}else{
					filterItems.push(groupMenu);
				}
				target.data("exsitKeys",existKeys);
				target.data("filterItems",enumValues);
			}
			//得到类型默认提供的筛选项
			if(filter.defaultFilters !== false){
			   var defaults = compare.getDefaultFilterItems() || [];
			   defaults.push({operation : "empty", unique : true},{operation : "unEmpty", unique : true})
			   filterItems.push({children : defaults});
			}
			return filterItems;
		},
		mergeItems : function(items1,items2){
			//计录数据，避免重复
			var existKeys = {};
			$.each(items1.children,function(i,item){
				existKeys[item.value] = true;
			});
			$.each(items2,function(i,item){
				if(item.children){
					this.buildItems(items1,item.children);
				}else{
					!existKeys[item.value] && items1.children.push(item);
				}
			});
		},
		// 数据排序比较方法
		arrayCompare : function(val1, val2){
		    if(val1 < val2){
		        return 1;
		    }else if(val1 > val2){
		        return -1;
		    }else{
		        return 0;
		    }
		},
		// 生成按天枚举菜单项
		buildDayEnumItems:function(filter,value, groupMenu, enumValues, existKeys){
			// 开始时间
			if(typeof value == "object" && filter.valueField && !(value instanceof  Date)){
				value = value[filter.valueField];
			}
			var startTime = Ccay.Format.toDate(value, Ccay.Config.Format.sysDate),
				dateStr = Ccay.Format.toDateStr(startTime);
			if(Ccay.DataHelper.hasValue(value) && !existKeys[dateStr]){
				// 开始时间处理,时间清0
				startTime = dataFilter.dateSetting(startTime, 0);
				
				groupMenu.children.push({value : startTime,text : dateStr, operation:"dayFilter"});
				enumValues.push({value : startTime,text : dateStr, operation:"dayFilter"});
				//将已经添加过的value，设置一个标，放在缓存中，下次不用再添加
				existKeys[dateStr] = true;
			}
		},
		
		buildMenusByFilter : function(col, filterItems){
			//遍历filterItems，将过滤条件转换为 上下文菜单的menus参数
			var menus = [], filter = col.filter, css = filter.multi ? "filter-checkbox" : "";
			$.each(filterItems, function(i, item){
				if(item.children){
					var children = dataFilter.buildMenusByFilter(col,item.children);
					menus.push({children : children});
					//在多选的枚举后添加按钮
					(filter.enumable 
						&& menus.length 
						&& menus[menus.length-1].children 
						&& menus[menus.length-1].children[0].css == "filter-checkbox") 
						&& menus.push({
							css : "filter-enumable-btn",
							text: "<input type='button' class='applyfilter' field='{2}' value='{0}' /><input type='button' class='cancelfilter' value='{1}' />".formatValue($i18n("ccay.common.filter.applyfilter"),$i18n("ccay.common.button.cancel"),col.field)
						});
				}else{
					var operation = item.operation || OPTypes[0],display;
					var value = item.value ? item.value.valueOf() : item.value;
					if(value !== void 0){
						if(typeof col.renderer == "function"){
							display = col.renderer.call(col,item.value);
						}else if(typeof col.renderer =="object"){
							var data = {};
							data[col.field] = item.value;
							display = Ccay.UI.template(col.content,data);
						}
					}
					menus.push({
						op : operation, 
						css : item.unique ?   "" :  css,
						click : dataFilter.menuClick, 
						text: $i18n(item.text) || $i18n("ccay.common.filter." + operation).formatValue(display || value),
						value :value
					})
				}
			
			});
			return menus;
			
		},

		confirmFilter : function(grid,callback){
			var op = grid.op,  storage = op.Storage;
			if (storage && storage.cacheKey && storage.Cache.count() || !op._cache && grid.getRecords()) {
				Ccay.UI.confirm("ccay.common.filter.cleardata", function (result) {
					if (result) {
						grid.clearCache();
						callback && callback();
						dataFilter.filter(grid);
					}
				});
			}else{
				callback && callback();
				dataFilter.filter(grid);
			}
		},
		// 生成pagerOp中的filter串
		filter : function(grid){
			var op = grid.op;
			// 筛选条件
			op.pagerOp.pageInf.filter =  dataFilter.genFilterStr(grid);
			if(!op.remoteSort || op.lazyLoad){ 
				grid.reload("search",true);
			}else{
				grid.reload("search");
			}
			
			if(op.showTip){
				$("#_tip_"+grid.id).css({visibility : "hidden"})
				setTimeout(function(){
					$("#_tip_"+grid.id).hide().css({visibility : "inherit"})
				},500)
			}
		},
		// 生成筛选条件Str
		genFilterStr : function(grid){
			var op = grid.op, 
				filters = op._filters, 
				storage = op.Storage,
				columnMap = op._columnMap;
				conds = [];
			//服务端筛选，重请求数据库。
			//将本地筛选项目转为服务端筛选参数
			for(var field in filters){
				var items = [],filter = columnMap[field].filter;
				filters[field] && $.each(filters[field],function(){
					var opeator = OperationFactory.get(this.operation);
					if(opeator.getFilter){
						items = items.concat(opeator.getFilter(this.value))
					}else{
						items.push(this);
					}
				});
				$.each(items,function(){
					var val = this.value;
					//处理自定义数据转换
					filter.convert && (val = filter.convert(val));
					if(typeof val =="string"){
						val = encodeURIComponent(val);
					}
					var item = {"ft" : OPEnum[this.operation], fv : val, fn : field};
					if(this.relation){
						item.fr = 1; 
					}
					conds.push(item);
				})
			}
			op._filtersStr = Ccay.DataHelper.toJsonStr(conds).encodeURI();
			return op._filtersStr;
		},
		/**比较方法
		 * @param {string} operation  比较符号
		 * @param value {@dataType}  实际比较数据
		 * @param compareValue {array or  @dataType}  值或值数组。 如果是数组，则为或关系
		 * @param dataType {@dataType}  数据类型
		 */		
		compare : function(operation, value, compareValue,dataType){
			//根据当前数据类型获取 比较工具，如果获取不到，则使用string的比较工具
			var fnCompare =FilterTools.get(dataType)[operation], result = true;
			//判断当前数据类型的比较工具是否支持当前比较符，如果支持则继续比较
			if(fnCompare){
				//如果当前数据类型的比较工具，重写了比较方式，则直接调用改方式，否则调用通用操作符接口比较
				if( typeof(fnCompare) === "function"){
					result = fnCompare(value, compareValue);
				}else{
					result = OperationFactory.get(operation).compare(value, compareValue)
				}
			}
			return result;
				
		},
		filterItems : function(items, value, dataType){
			var result = -1, ret;
			for(var i = 0, item; item = items[i]; i++){
				//判断当前列类型是否支持改操作符过滤比较
				if(FilterTools.get(dataType)[item.operation]){
					ret = dataFilter.compare(item.operation,value, item.value, dataType);
					//判断结果是否已经被赋予比较结果值，如果未被初始化，则直接将赋值，否则，需要处理filter的关系符，并做逻辑处理
					if(result === -1){
						result = ret;
					}else{
						// 未配置relation的时候，做逻辑与处理，否则做 逻辑或处理
						result = item.relation ?  result || ret : result && ret;
					}
				}
			}
			return result;
		}
	};

	//根据筛选配置生成搜索条件
	var dataSearchFilter = {
			//初始化配置
		init:function(grid, op){
			var searchForm = $(op.operation.search.panel);
			//是否重新初始化，清空内容
			if(searchForm.hasClass('ccay-widget')){
				searchForm.empty().removeClass("ccay-widget");
				searchForm.data("xctrInited",false);
				//清空查询条件设置
				grid.op.pagerOp.pageInf.filter = "[]".encodeURI();
			}
			// 是否为搜索模式
			if(op.switchMode != "search"){
				return;
			}
			var xFormOption = {
				modal: this.createModal(grid, op),
				title: op.genSearchByFilter.title || $i18n("ccay.common.button.search"),
				renderType: "search",
				showHead:false,
				buttons:[{type:"imgBtn",text:"ccay.common.button.search",icon:"search",css:"default",attr:{eno:"search"}},
				         {type:"imgBtn",text:"ccay.common.button.reset",icon:"reset",attr:{eno:"reset"}}],
				operation: {
					search: function (e, form) {
						if (!form.valid()) {
							return;
						}
						//得到表单数据
						var data = form.getValue();
						var conds = [];
						//迭代取出表单数据与对应的Filter
						$.each(data,function(field){
							//取得Filter对象
							var filedMap = form.op.modal[field];
							var val = this;
							if(filedMap.field.indexOf("_")>0){
								filedMap.field =  filedMap.field.replaceAll("_",".");
							}
							if(val.value != undefined){
								val = val.value;
							}
							if(val){
								//设置为包括
								var op = OPEnum["includes"];
								//是否为number类型，
								if((val instanceof Number || filedMap.type == "date" || filedMap.type == "enum" || filedMap.type == "ldap") &&　filedMap.layout != "range"){
									//使用全等
									op = OPEnum["equals"]
								}
								if(filedMap.type != "date" && filedMap.type != "datetime"){
									val = encodeURIComponent(val);
								}
								//处理自定义数据转换
								filedMap.filter && filedMap.filter.convert && (val = filedMap.filter.convert(val));
								if(filedMap.layout == "range"){//是否是范围查询
									var index = filedMap.field.lastIndexOf(".start");
									if(index !=-1){
										conds.push({"ft" : OPEnum["equalsGreatThan"], fv : val, fn : filedMap.field.substring(0,index)});
									}
									index = filedMap.field.lastIndexOf(".end");
									if(index !=-1){
										conds.push({"ft" : OPEnum["equalsLessThan"], fv : val, fn : filedMap.field.substring(0,index)});
										}
								}else{
									conds.push({"ft" : op, fv : val, fn : filedMap.field});	
								}
							}

						});
						//添加条件，执行查询
						grid.op.pagerOp.pageInf.filter = Ccay.DataHelper.toJsonStr(conds).encodeURI();
						if(!grid.op.remoteSort || grid.op.lazyLoad){ 
							grid.reload("search",true);
						}else{
							grid.reload("search");
						}
					},
					reset:function(e,form){
						form.setValue({});
						form.dom.find(".error-ctr").removeClass("error error-ctr");
						form.dom.find("label.error").hide();
					}
				}
			}
			
			searchForm.xForm(xFormOption);
		},
		addField:function(grid, op){
			var fileds = [];
			if(op.columns){
				//遍历columns，根据filed=true 生成查询
				$.each(op.columns,function(){
					//是否有配filter 并且非隐藏列
					if(this.filter && !this.hidden){
						var filedMap = {};
						filedMap.field = this.field;
						//filedMap.alias=this.field;
						//如果是xxx.xx 方式，则用'_' 代替
						if(this.field.indexOf(".")>0){
							filedMap.field =  this.field.replaceAll("\\.","_");
							//filedMap.alias =  this.field.replaceAll("\\.","_");
						}
						filedMap.name = $i18n(this.header);
						//是否是自定义筛选项
						if(this.filter.defines && !(this.type == "integer" || this.type == "int"|| this.TypeError == "floatRequ")){
							filedMap.type = "enum";
							$.each(this.filter.defines,function(){
								this.text = $i18n(this.text);
							})
							filedMap.format = {data:this.filter.defines || {}, valueField: "value", displayField: "text"};	
						}else if(this.filter.enumable && this.filter.ajax){//是否动态数据枚举项
							filedMap.type = "enum";
							filedMap.format = {service:"REST:"+this.filter.ajax.url, valueField: this.filter.valueField,displayField:this.filter.displayField || this.filter.valueField};
						}else if(this.type == "textarea"){
							filedMap.type = "text";
							filedMap.format = this.format || {};
						}else{
							filedMap.type = this.type;
							filedMap.format = this.format || {};
						}
						filedMap.editorOp =  this.editorOp || {};
						filedMap.filter = this.filter;
						//是否为范围查询
						if(this.filter.range){
							fileds.push({type:this.type,field:filedMap.field+"_start",editorOp:{id:filedMap.field+"_start"},layout:"range",enable:false,format:this.format || {}});
							fileds.push({type:this.type,field:filedMap.field+"_end",layout:"range", enable:false,format:this.format || {},rule:{dateCompare:["#"+filedMap.field+"_start"]}});
							filedMap.layout = "range";
							filedMap.renderTmpl = "${searchModel."+filedMap.field+"_start}${searchModel."+filedMap.field+"_end}";
						}
						fileds.push(filedMap);
					}
				});
			}
			return fileds;
		},
		createModal:function(grid, op){
			var searchModal={
				modalName:"searchModel",
				fields:this.addField(grid, op)
			};
			return Ccay.Modal.create(searchModal);
		}
	}
	//注册数据筛选插件
	Ccay.UI.XControl.addPlugin("XGrid", "dataFilter", {
		
		preInit : function(grid, op){
				op.headMenus = [];
				dataFilter.init(grid, op);
				op.beforeColResize = function(){
					this.getHeadPanel().children(".ccay-contextmenu-list.ccay-popup").hide();
				}
		},
	    build: function (grid, op) {
	    	if(op.allowFilter && op.switchMode != "search"){
	    		//用来记录grid当前数据的正在使用的过滤条件
	    		!op._filters && (op._filters ={}); 
	    		//自定义
	    		!op._cusFilters && (op._cusFilters ={});
	    		//输入框
	    		!op._inputFilters && (op._inputFilters ={});
	    		op.handler.setColumn.add(function(grid, col){
	    			if(col.filter){
	    				var cssName = op._filters[col.field] ? " filterable filter" : " filterable"
	    				col._headCss +=  cssName;
	    			}
	    		});
	    	}
	    	
	    	if(!op.pagerOp.pageInf.filter){
	    		op.pagerOp.pageInf.filter = "[]".encodeURI();
	    	} 
			if(op.allowFilter && op.genSearchByFilter){
    			dataSearchFilter.init(grid, op);
    		}
	    },
	    clear: function (grid, op, oldOp) {
	    	op._filters = oldOp._filters;
	    	op._inputFilters = oldOp._inputFilters;
	    	op._cusFilters =  oldOp._cusFilters;
	    	op.pagerOp.pageInf.filter =  oldOp.pagerOp.pageInf.filter;
	    }
	});
	// manager扩展
	Ccay.UI.XControl.extendIManager("XGrid", {
		// 获得已筛选的条件
		getFilters:function(field){
			return field ? this.op._filters[field] || [] : this.op._filters || {};
		},
		// 获得已筛选的条件的拼接字符串
		getFiltersStr:function(){
			return this.op._filtersStr || "[]".encodeURI();
		}
	});
	
})(Ccay.UI.IGrid);